package com.hsurosy.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.hsurosy.domain.activity.model.entity.DeliveryOrderEntity;
import com.hsurosy.domain.activity.service.IRaffleActivityAccountQuotaService;
import com.hsurosy.domain.credit.event.CreditAdjustSuccessMessageEvent;
import com.hsurosy.types.enums.ResponseCode;
import com.hsurosy.types.event.BaseEvent;
import com.hsurosy.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-26 0:19
 * @Description 积分调整成功消息
 * @Version: v1.0.0
 */
@Slf4j
@Component
public class CreditAdjustSuccessCustomer {

    @Value("${spring.rabbitmq.topic.credit_adjust_success}")
    private String topic; // RabbitMQ 消息主题

    @Resource
    private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService; // 抽奖活动账户配额服务

    /**
     * 监听积分账户调整成功消息队列
     *
     * @param message 消息内容，包含积分调整的具体信息（JSON 格式）
     */
    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.credit_adjust_success}"))
    public void listener(String message) {
        try {
            log.info("监听积分账户调整成功消息，进行交易商品发货 topic: {} message: {}", topic, message);
            // 解析消息为事件对象
            BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage>>() {
                    }.getType());
            CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage creditAdjustSuccessMessage = eventMessage.getData();

            // 构建发货订单实体
            DeliveryOrderEntity deliveryOrderEntity = new DeliveryOrderEntity();
            deliveryOrderEntity.setUserId(creditAdjustSuccessMessage.getUserId());
            deliveryOrderEntity.setOutBusinessNo(creditAdjustSuccessMessage.getOutBusinessNo());

            // 调用发货逻辑
            raffleActivityAccountQuotaService.updateOrder(deliveryOrderEntity);
        } catch (AppException e) {
            // 处理业务异常，特别是重复消费的情况（唯一索引冲突）
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听积分账户调整成功消息，进行交易商品发货，消费重复 topic: {} message: {}", topic, message, e);
                return;
            }
            throw e;
        } catch (Exception e) {
            // 捕获其他异常并记录日志
            log.error("监听积分账户调整成功消息，进行交易商品发货失败 topic: {} message: {}", topic, message, e);
            throw e;
        }
    }

}
